package cn.com.xinjinfu.pdoulcProduct.activity.recharge;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import cn.com.xinjinfu.pdoulcProduct.R;
import cn.com.xinjinfu.pdoulcProduct.activity.base.BaseActivity;
import cn.com.xinjinfu.pdoulcProduct.common.ConstantValues;
import cn.com.xinjinfu.pdoulcProduct.engine.DataHandler;
import cn.com.xinjinfu.pdoulcProduct.entity.User;
import cn.com.xinjinfu.pdoulcProduct.entity.WithdrawDepositBean;
import cn.com.xinjinfu.pdoulcProduct.manager.AccountManager;
import cn.com.xinjinfu.pdoulcProduct.manager.JSONManager;
import cn.com.xinjinfu.pdoulcProduct.manager.L;
import cn.com.xinjinfu.pdoulcProduct.manager.TitleManager;
import cn.com.xinjinfu.pdoulcProduct.manager.UIManager;
import cn.com.xinjinfu.pdoulcProduct.utils.BankImgUtils;
import cn.com.xinjinfu.pdoulcProduct.utils.EditTextUtil;
import cn.com.xinjinfu.pdoulcProduct.utils.TextViewUtil;

/**
 * 提现
 * Created by android-adt on 2016/1/5.
 */
public class ActWithdrawDeposit extends BaseActivity{

    private ImageView img_bankcard;
    private TextView tv_error_hint,tv_shouxu_hint, tv_bank_name,
            tv_bankcart_num,tv_can_withdraw_money,wenxin_hind;
    private User user;
    private int canwethdrawNum,dayCount;
    private Button bt_withdraw;
    private EditText et_my_withdraw_money;
    private double mWithdrawMoney;
    private RequestQueue requen;
    private Dialog dg;
    private RelativeLayout withdrawlimit;
    private double balance,withdrawalFee,withdrawalSill,gainMoneylowestLimit,dayWithDrawalAmount,thisdayCount;
    private  WithdrawDepositBean withdrawDepositBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_withdraw_deposit);
        //初始化头布局
        TitleManager.showTitle(this, "提现", "");
        requen = Volley.newRequestQueue(this);
        user = AccountManager.getInstance().getUser();
        Bundle bundle = new Bundle();
        bundle = this.getIntent().getExtras();
        balance = bundle.getDouble("balance");
        withdrawalSill = 100;
        initView();
        initUpData();
        Request();
    }

    public void initView() {
        tv_can_withdraw_money = (TextView) findViewById(R.id.tv_can_withdraw_money);
        //错误提示
        withdrawlimit = (RelativeLayout) findViewById(R.id.withdrawlimit);
        tv_error_hint = (TextView) findViewById(R.id.tv_error_hint);
        tv_shouxu_hint = (TextView) findViewById(R.id.tv_shouxu_hint);
        wenxin_hind = (TextView) findViewById(R.id.wenxin_hind);
        tv_bank_name = (TextView) findViewById(R.id.tv_bank_name);
        tv_bankcart_num = (TextView) findViewById(R.id.tv_bankcart_num);
        img_bankcard = (ImageView) findViewById(R.id.img_bankcard);
        //要提现的金额
        et_my_withdraw_money = (EditText) findViewById(R.id.et_my_withdraw_money);
        EditTextUtil.setPricePoint(et_my_withdraw_money);
        et_my_withdraw_money.addTextChangedListener(mTextWatcher);
        bt_withdraw = (Button) findViewById(R.id.bt_withdraw);
    }

    public void initUpData() {
        if (user != null) {
            tv_can_withdraw_money.setText(TextViewUtil.getSumLength(balance));
            if (user.getBank() == -1) {
                tv_bank_name.setText(user.getBank_name());
                String id = user.getAccount();
                String show_id = "**** **** **** " + id.substring(id.length() - 4);
                tv_bankcart_num.setText(show_id);
                int x = new BankImgUtils().mBank(false, user.getBank_code());
                int y = new BankImgUtils().mBank(true, user.getBank_code());
                img_bankcard.setImageResource(x);
                tv_bank_name.setBackgroundColor(y);
            }
        }
        bt_withdraw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_my_withdraw_money.getText().toString().equals("") || mWithdrawMoney == 0) {
                    tv_error_hint.setVisibility(View.VISIBLE);
                    tv_error_hint.setText("您输入金额有误，请重新输入");
                } else {
                    if (user.getCurrUser().isSetPayPwd()) {
                        PayPwdDilog mPayPwdDilog = new PayPwdDilog(ActWithdrawDeposit.this,et_my_withdraw_money.getText().toString());
                        mPayPwdDilog.setSuccessListener(new PayPwdDilog.SuccessListener() {
                            @Override
                            public void onPwdSuccess(final String password) {
                                //跳转页面
                                UIManager.showTrandDilog(ActWithdrawDeposit.this, EditTextUtil.getStringEditText(et_my_withdraw_money),
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                if (!EditTextUtil.compareSize(gainMoneylowestLimit, mWithdrawMoney)) {
                                                    tv_error_hint.setVisibility(View.VISIBLE);
                                                    tv_error_hint.setText("您输入的金额不足" + gainMoneylowestLimit + "元提现起点金额；");
                                                    bt_withdraw.setEnabled(false);
                                                } else {
                                                    //发送提现请求
                                                    loginRequest(password);
                                                }
                                            }
                                        });
                            }
                        });
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra("falg", 0);
                        intent.setClass(ActWithdrawDeposit.this, TradePWD.class);        //跳转到支付密码设置页
                        startActivity(intent);
                    }
                }
            }
        });
    }

    /**
     * 提现页面初始化网络请求
     */
    private void Request() {
        dg = UIManager.getLoadingDialog(this);
        dg.setCanceledOnTouchOutside(false);
        dg.show();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1305");
            parameters.put("id", user.getCurrUser().getSign());
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jobj) {
                    dg.dismiss();
                    withdrawDepositBean = JSON.parseObject(jobj.toString(), WithdrawDepositBean.class);
                    if (JSONManager.getError(jobj)==0){
                        UpData();
                    }
                }
            }, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }

    public void UpData() {
        balance = withdrawDepositBean.getTodayCanWithdrawAmount();
        gainMoneylowestLimit = withdrawDepositBean.getGainMoneylowestLimit();
        withdrawalFee = withdrawDepositBean.getWithdrawalFee();
        withdrawalSill = withdrawDepositBean.getWithdrawalSill();
        int withdrawLimit = withdrawDepositBean.getWithdrawLimit();
        int withdrawLimitHint = withdrawDepositBean.getWithdrawLimitHint();
        dayCount = withdrawDepositBean.getDayCount();
        dayWithDrawalAmount = withdrawDepositBean.getDayWithDrawalAmount();
        int freenumber = withdrawDepositBean.getWithdrawalfreenumber();
        int hasNum = withdrawDepositBean.getUserWithdrawalCount();
        int dayTime = withdrawDepositBean.getDayTime();
        canwethdrawNum = freenumber-hasNum;
        if (canwethdrawNum < 0) { canwethdrawNum = 0;}
        tv_can_withdraw_money.setText(TextViewUtil.getSumLength(balance));
        if (withdrawLimit > 0){
            tv_shouxu_hint.setText("提现手续费：" + TextViewUtil.getStringTwoLength(withdrawalFee) + "元，将从申请提现金额中扣除");
        }else {
            tv_shouxu_hint.setText("本月剩余免费提现次数：" + canwethdrawNum + "次");
        }
        if (withdrawLimitHint>0){
            withdrawlimit.setVisibility(View.VISIBLE);
        }else {
            withdrawlimit.setVisibility(View.GONE);
        }
        String info = "1、投资用户每月前"+freenumber+"笔提现免费，超过"+freenumber+"笔收取每笔"+TextViewUtil.getStringTwoLength(withdrawalFee)
                +"元手续费；未投资用户无法享受免费提现；\n" +
                "2、每日最多提现"+dayTime+"次，提现上限"+ (dayCount/10000) +"万元；\n" +
                "3、到账时间：下个工作日15:00后；\n"+
                "4、若需变更银行卡，请联系客服人工审核。\n";
        wenxin_hind.setText(info);
    }


    /**
     * 提现网络请求
     */
    private void loginRequest(String password) {
        dg.show();
        user = AccountManager.getInstance().getUser();
        if (user != null) {
            final Map<String, String> parameters = DataHandler.getParameters("1306");
            parameters.put("id", user.getCurrUser().getSign());
            parameters.put("withdrawalAmount", EditTextUtil.getStringEditText(et_my_withdraw_money));
            parameters.put("dealPsword",DataHandler.encrypt3DES(password));
            JsonObjectRequest request = new JsonObjectRequest(DataHandler.getBuildUrl(parameters), null, succeedRespon, error);
            request.setRetryPolicy(new DefaultRetryPolicy(ConstantValues.TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
            requen.add(request);
        }
    }

    private Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dg.dismiss();
            DataHandler.errorHandler(ActWithdrawDeposit.this, error);
        }
    };

    private Response.Listener<JSONObject> succeedRespon = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject jobj) {
            L.d("提现返回数据=================================" + jobj);
            dg.dismiss();
            int code = JSONManager.getError(jobj);
            if (code == 0) {
                UIManager.showSuccessFailDilog(ActWithdrawDeposit.this, "提现成功!", code, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            } else {
                UIManager.showSuccessFailDilog(ActWithdrawDeposit.this, "提现失败!", code, null);
            }
        }
    };


    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                                  int arg3) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            mWithdrawMoney = EditTextUtil.getDoubleEditText(et_my_withdraw_money);
            tv_error_hint.setVisibility(View.GONE);
            if (!EditTextUtil.compareSize(mWithdrawMoney, balance)) {
                tv_error_hint.setVisibility(View.VISIBLE);
                tv_error_hint.setText("您输入的金额已超出可提现金额");
                bt_withdraw.setEnabled(false);
            } else {
                if ((int)balance<withdrawalSill){
                    if (mWithdrawMoney != balance){
                        tv_error_hint.setText("账户余额不足" + withdrawalSill + "元, 请全部提现！");
                                tv_error_hint.setVisibility(View.VISIBLE);
                        bt_withdraw.setEnabled(false);
                    }else {
                        bt_withdraw.setEnabled(true);
                    }
                }else {
                    if ((int)mWithdrawMoney<withdrawalSill){
                        tv_error_hint.setText("提现金额不能小于"+withdrawalSill+"元");
                        tv_error_hint.setVisibility(View.VISIBLE);
                        bt_withdraw.setEnabled(false);
                    }else {
                        bt_withdraw.setEnabled(true);
                    }
                }
                if (canwethdrawNum == 0 && withdrawalFee>=balance){
                    tv_error_hint.setText("免费提现次数为0，账户余额大于"+TextViewUtil.getStringTwoLength(withdrawalFee)+"元方可提现；");
                    tv_error_hint.setVisibility(View.VISIBLE);
                }
                if (mWithdrawMoney > (dayCount - dayWithDrawalAmount)){
                    tv_error_hint.setVisibility(View.VISIBLE);
                    tv_error_hint.setText("您输入的金额已超出今日可提现金额上限");
                    bt_withdraw.setEnabled(false);
                }

            }
        }
    };
}